package com.part2.action.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.part2.action.common.validator.Validator;

public class ToHTML {
	private static URLConnection connection;

	private static void connect(String urlString) {
		try {
			URL url = new URL(urlString);
			connection = url.openConnection();
			System.out.println(">>>>>>url" + url.getPath());
			// System.out.println(connection.getClass());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** */
	/**
	 * 生成静态html
	 * 
	 * @param path
	 *            生成的html保存的地址
	 * @param nid
	 *            用来生成网页的名称,保证每个文件名的唯一性
	 * @param url
	 *            读取动态网页的url地址
	 * @return no return value
	 */
	public static void makeHTML(String path, String nid, String url,String type) {
		String filePath = path;
		String id = nid;
		String fileTitle = Encode.encodeByMD5(id);
		if(Validator.isNotNull(type))
			fileTitle = nid;
		String htmlFilePath = filePath + fileTitle + ".html";
		BufferedReader in = null;
		connect(url);
		try {
			in = new BufferedReader(new InputStreamReader(connection
					.getInputStream()));

			String inputLine, tmp = "";
			while ((inputLine = in.readLine()) != null) {
				tmp += inputLine + "\n";
			}
			File fileDir = new File(filePath);
			if (!fileDir.exists()) {
				fileDir.mkdir();
				System.out.println(":::::::::::makeDir::::::::::" + fileDir);
			}
			File file = new File(htmlFilePath);
			BufferedWriter output = new BufferedWriter(new FileWriter(file));
			output.write(tmp);
			output.close();
//			System.out.println(tmp);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}